package com.lanou.userLogin.cart.web.servlet;

import com.lanou.userLogin.cart.domin.CartBook;
import com.lanou.userLogin.cart.domin.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/myCartServlet")
public class MyCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        List<CartItem> myCart = (List<CartItem>) session.getAttribute("cartList");
        if (myCart.size() == 0) {
            req.getRequestDispatcher("/jsps/main.jsp").forward(req, resp);
        } else {
            for (CartItem cartItem : myCart) {
                System.out.println(cartItem);
            }

            double sumMoney = 0;
            for (CartItem cartItem : myCart) {
                sumMoney += cartItem.getCount() * cartItem.getBook().getPrice();
                System.out.println(sumMoney);
            }

            req.setAttribute("cartList", myCart);
            req.setAttribute("sumMoney", sumMoney);
            req.getRequestDispatcher("/jsps/cart/list.jsp").forward(req, resp);

        }
    }
}
